package com.cxw.healthserver.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.cxw.healthserver.entity.Archive
import com.cxw.healthserver.mapper.ArchiveMapper
import com.cxw.healthserver.response.BaseResponse
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.json.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @createTime 2024/6/25 22:44
 * @author 崔兴旺
 * @description
 */
@Service
class ArchiveService {
    @Autowired
    private lateinit var residentService: ResidentService

    @Autowired
    private lateinit var archiveMapper: ArchiveMapper

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    fun queryArchive(username: String, idNumber: String): JsonNode? {
        val archive = archiveMapper.selectOne(QueryWrapper<Archive>().eq("username", username).eq("idNumber", idNumber))
        if (archive != null) {
            return objectMapper.readTree(archive.json)
        }
        return null
    }


    fun saveArchive(username: String, jsonStr: String): BaseResponse<Any> {
        val jsonObject = JSONObject(jsonStr)
        val personalInfoJO = jsonObject.optJSONObject("personalInfo", null)
        val idNumber = personalInfoJO?.optString("idNumber", null)
        if (idNumber.isNullOrBlank()) {
            return BaseResponse.fail("档案中缺少idNumber")
        }
        var archive = archiveMapper.selectOne(QueryWrapper<Archive>().eq("username", username).eq("idNumber", idNumber))
        var isAdd = false
        if (archive == null) {
            archive = Archive()
            isAdd = true
        }
        archive.username = username
        archive.idNumber = idNumber
        archive.json = jsonStr
        val rows = if (isAdd) {
            archiveMapper.insert(archive)
        } else {
            archiveMapper.updateById(archive)
        }
        if (rows >= 0) {
            residentService.recordHasArchive(username,idNumber)
            return BaseResponse.success(null)
        }
        return if (isAdd) {
            BaseResponse.fail("新增档案失败,rows:${rows}")
        } else {
            BaseResponse.fail("更新档案失败,rows:${rows}")
        }
    }
}